﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using EMC;
using System.IO;
using System.Reflection;

namespace FileServer
{

    public class Connections
    {
        private Socket listenSocket;
        private String addressOfServer;
        private String downloadTo;
        private bool running;

        public Connections(string dnsaddress, String downloaddir)
        {
            addressOfServer = dnsaddress;
            downloadTo = downloaddir;
        }

        public void stop()
        {
            running = false;
            listenSocket.Close();
        }

        public void start()
        {
            running = true;
            ListenForClients();
        }

        private void ListenForClients()
        {
            listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            IPAddress[] ipAddress = Dns.GetHostAddresses(addressOfServer);
            listenSocket.Bind(new IPEndPoint(ipAddress[0], 5656));


            while (running == true)
            {
                listenSocket.Listen(100);
                Socket newcon = listenSocket.Accept();

                Thread handelness = new Thread(new ParameterizedThreadStart(HandleClient));
                handelness.Name = "Handle the Client";
                handelness.Start(newcon);
            }

            listenSocket.Close();
        }

        private void HandleClient(object client)
        {

            Socket clientSock = (Socket)client;

            while (running == true)
            {
                string mess = recMess(clientSock);
                string[] message = mess.Split(',');

                if (message[0] == "$FRANK")
                {
                    if (message[1] == "FILE")
                    {
                        if (message[2] == "UPLOAD")
                        {
                            int bufferSize = 1000;
                            System.Diagnostics.Debug.WriteLine("Reciving Data");
                            int receivedBytesLen = 0;
                            FileStream neofiledata = new FileStream(downloadTo, FileMode.Append, FileAccess.Write);

                            byte[] buffer = new byte[bufferSize];

                           do
                            {
                                Thread.Sleep(1);
                                receivedBytesLen = clientSock.Receive(buffer);
                                neofiledata.Write(buffer, 0, bufferSize);
                                //System.Diagnostics.Debug.WriteLine("Bytes Recived: " + receivedBytesLen);

                            } while (bufferSize == receivedBytesLen);
                            System.Diagnostics.Debug.WriteLine("File Completed");
                            neofiledata.Close();

                        }
                        else if (message[2] == "DOWNLOAD")
                        {
                            System.Diagnostics.Debug.WriteLine("Retrive the File");
                        }
                    }
                    else if (message[1] == "LOGIN")
                    {

                        string dbConfigFile = Path.GetDirectoryName(Assembly.GetAssembly(typeof(Program)).CodeBase) + @"/db_settings.xml";
                        databaseConfiguration config = new databaseConfiguration(dbConfigFile);
                        UserManagement userman = new UserManagement(config);

                        string username = message[2];
                        string password = message[3];

                        //System.Diagnostics.Debug.WriteLine("\nAuth user: " + userman.authenticateUser(username, password));

                        if (userman.authenticateUser(username, password))
                        {
                            sendMessage(clientSock, "$CLIENT,LOGIN,OK,");
                        }
                        else
                        {
                            sendMessage(clientSock, "$CLIENT,LOGIN,BAD,");
                        }
                    }
                    else if (message[1] == "USER")
                    {
                        System.Diagnostics.Debug.WriteLine("User Functions");
                        if (message[2] == "CREATE")
                        {
                            System.Diagnostics.Debug.WriteLine("Create a User");
                        }
                        else if (message[2] == "GET")
                        {
                            System.Diagnostics.Debug.WriteLine("Get User Data");
                        }
                        else if (message[2] == "DELETE")
                        {
                            System.Diagnostics.Debug.WriteLine("DELETE A USER");
                        }
                    }
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("Messge recived is not the Proper format");
                }


            }
        }
        private void sendMessage(Socket clientSocket, string protocolMessage)
        {

            byte[] sendmess = Encoding.UTF8.GetBytes(protocolMessage);

            System.Diagnostics.Debug.WriteLine("Message sent: " + protocolMessage);

            clientSocket.Send(sendmess);

        }

        private string recMess(Socket incomming)
        {
            byte[] buffer = new byte[1024];

            incomming.Receive(buffer);
            System.Diagnostics.Debug.WriteLine("Message Recived: " + Encoding.UTF8.GetString(buffer));
            return Encoding.UTF8.GetString(buffer);

        }
    }
}
/*#############SERVER PROTOCOL STRINGS++++++++++++++++
 * Start by selecting the Server
 * $FRANK
 * now Add what follows 
 */

/*##############FILE PROTOCOL STRINGS++++++++++++++++++++++
 *  Define what catergoy
 *  "FILE"
 * Define Function
 *      UPLOAD  Upload a file
 *      DOWNLOAD Download a File
 *EG
 *  To Send a File use the string 
 *  $FRANK,FILE,UPLOAD,<PARAMERTERS>,
 *  
 */


/*##############USER PROTOCOL STRINGS++++++++++++++++++++++
 *  Define what catergoy
 *  "USER"
 * Define Function
 *      CREATE  Create a User
 *      GET     Get User Data
 *      DELETE  DELETE A USER
 */